package com.heima.search.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApAssociateWords;
import com.heima.search.service.IApAssociateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author : wuqiang
 * @date : 2022年10月23日
 */
@Service
public class ApAssociateServiceImpl implements IApAssociateService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult searchAssociate(ApArticleSearchDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getSize() < 0 || ObjUtil.isNull(dto.getSize())) {
            dto.setSize(5);
        }
        if (StringUtils.isBlank(dto.getSearchWords())) {
            return null;
        }
        Query query = new Query(Criteria.where("associateWords").regex(dto.getSearchWords()));
        query.limit(dto.getSize());
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApAssociateWords> apAssociateWords = mongoTemplate.find(query, ApAssociateWords.class);
        return ResponseResult.okResult(apAssociateWords);
    }
}
